(function (exports) {
    var $ = null;
    /*
    required string Code 			= 1;	//道具Code
    required int32	Quantity 		= 2;	//道具数量
    required int32	IsWare 	    	= 3;	//道具是否在装备中
    required int64	Seconds 	    = 4;	//时间类型道具剩余秒数
    optional int32	IsSucceed  	    = 5;	//是否成功      1成功  0失败
    optional int64  ChangeQuantity  = 6;	//变化数量 数量类型代表数量   时间类型代表剩余秒数
    optional string goodsfuntype	= 7;	//道具类型 当通过类型来获取道具时，该字段有值
    */

    var BagLayer = cc.Layer.extend({
        showDesc: false,
        TagType: ['item', 'bill', 'tickets'],
        TagTypeName: ['道具', '话费', '门票'],
        BagAllData: [],
        CurBagData: [],
        curDataIndex: 0, // 0道具 1 话费 2 门票
        onEnter: function () {
            cc.Layer.prototype.onEnter.call(this);
            var data = {
                UserID: gameData.uid + "",
                GameID: app.area + "",
                AppID:app.appId + "",
                GoodsKeys: []  //获取所有道具
            };
            network.sendProto(1055, data);
        },
        addListener: function (code, listener) {
            network.addListener(code, listener, this);
        },
        onExit: function () {
            cc.Layer.prototype.onExit.call(this);
            ItemData.setItemChange([]); //已查看 设置为[]
            network.removeListenersForTarget(this);
        },
        ctor: function () {
            this._super();
            var that = this;

            var scene = loadNodeCCS(res.BagLayer_json, this);
            $ = create$(this.getChildByName('Layer'));
            this._$ = $;

            // var size = $('bg').getContentSize();
            // var piaodai = getCreateRoomAni(7);
            // piaodai.setPosition(size.width/2, size.height-50);
            // $('bg').addChild(piaodai);

            $('tip_no').setVisible(false);
            $('charge_call_node').setVisible(false);

            this.addListener(1056, function (data) {
                hideLoading();

                var GoodsList = data.GoodsList;
                that.BagAllData = GoodsList;
                //测试数据
                // that.BagAllData = [{
                //     Code: "bill_1",
                //     Quantity: 10,
                //     IsWare: 1,
                //     Seconds: 999999,
                // }];
                that.selectTab(that.curDataIndex);

            });

            TouchUtil.setOnclickListener($('btn_close'), function (node) {
                // that.removeFromParent(true);
                that.getParent().removeFromParent(true);
            });
            TouchUtil.setOnclickListener($('btn_daoju1'), function (node) {
                that.selectTab(0);
                that.setWeiduMegNum(0, $('btn_daoju1'));
            });

            TouchUtil.setOnclickListener($('btn_huafei1'), function (node) {
                that.selectTab(1);
                that.setWeiduMegNum(0, $('btn_huafei1'));
            });

            TouchUtil.setOnclickListener($('btn_menpiao1'), function (node) {
                that.selectTab(2);
                that.setWeiduMegNum(0, $('btn_menpiao1'));
            });

            //小红点提示
            that.judgeRedNum(ItemData.getItemChange());
        },
        judgeRedNum: function (_changeInfo) {
            var that = this;

            var count1 = 0;
            var count2 = 0;
            var count3 = 0;
            for (var i = 0; i < _changeInfo.length; i++) {
                var _itemInfo = ItemData.getItemInfoByCode(_changeInfo[i].Code);
                if (_itemInfo.TagType == that.TagType[0]) {
                    count1++;
                } else if (_itemInfo.TagType == that.TagType[1]) {
                    count2++;
                } else if (_itemInfo.TagType == that.TagType[2]) {
                    count3++;
                }
            }
            that.setWeiduMegNum(count1, $('btn_daoju1'));
            that.setWeiduMegNum(count2, $('btn_huafei1'));
            that.setWeiduMegNum(count3, $('btn_menpiao1'));
        },
        setWeiduMegNum: function (num, node) {
            if (!$ || !$("btn_daoju1")) {
                return;
            }
            $("numbg", node).setVisible(num > 0);
        },
        selectTab: function (idx) {
            this.curDataIndex = idx;
            var btnTable = ['btn_daoju', 'btn_huafei', 'btn_menpiao'];
            for (var i = 0; i < btnTable.length; i++) {
                (function (i) {
                    if (idx == i) {
                        $(btnTable[i] + '1').setVisible(false);
                        $(btnTable[i] + '2').setVisible(true);
                    } else {
                        $(btnTable[i] + '1').setVisible(true);
                        $(btnTable[i] + '2').setVisible(false);
                    }
                })(i);
            }

            this.initBagLayer(idx);
        },

        initBagLayer: function (idx) { //idx 0 道具 1 话费 2 门票
            var that = this;

            that.curDataIndex = idx;
            that.CurBagData = [];//保存当前展示的物品

            for (var i = 0; i < that.BagAllData.length; i++) {
                var code = that.BagAllData[i].Code;
                var TagType = ItemData.getItemInfoByCode(code).TagType;
                if (that.TagType[that.curDataIndex] == TagType) {
                    that.CurBagData.push(that.BagAllData[i]);
                }
            }

            $('tip_no').setVisible(that.CurBagData.length <= 0);

            if (that.tableview) {
                tableViewRefresh(that.tableview); //刷新一遍 用于查询
            } else {
                var tableviewLayer = $('tableview');
                var tableview = new cc.TableView(that, cc.size(tableviewLayer.getContentSize().width, tableviewLayer.getContentSize().height));
                tableview.setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL);
                tableview.setVerticalFillOrder(cc.TABLEVIEW_FILL_TOPDOWN);
                tableview.setPosition(0, 0);
                tableview.setDelegate(that);
                tableview.setBounceable(true);
                tableviewLayer.addChild(tableview);
                that.tableview = tableview;
            }
        },
        //点击cell
        tableCellTouched: function (table, cell) {

        },
        tableCellSizeForIndex: function (table, idx) {
            return cc.size(940, 230);
        },
        tableCellAtIndex: function (table, idx) {

            var that = this;

            var cell = table.dequeueCell();
            if (cell == null) {
                cell = new cc.TableViewCell();
                // var row0 = ccs.load(res.BagItem_json, 'res/').node;
                var row0 = loadNodeCCSItem(res.BagItem_json);
                row0.setName('cellrow');
                cell.addChild(row0);
            } else {
            }
            var Layer = cell.getChildByName('cellrow');

            var node_0 = $('node_0', Layer);
            node_0.setVisible(false);
            for (var i = 0; i < 4; i++) {
                (function (i) {
                    var node = $('node_' + (i + 1), Layer);
                    if (!node) {
                        console.log('node  si    ===== '+i)
                        node = duplicateNode(node_0);
                        node.setPositionX(node_0.getPositionX() + i * 235)
                        node.setPositionY(node_0.getPositionY());
                        node_0.getParent().addChild(node);
                        node.setName('node_' + (i + 1));
                    }
                    node.setVisible(false);

                    var curIdx = idx * 4 + i;
                    if (that.CurBagData[curIdx]) {
                        var data = that.CurBagData[curIdx]; //当前node的信息
                        node.setVisible(true);

                        var code = data.Code;
                        var num = data.Quantity; //数量
                        var seconds = data.Seconds;

                        var Item_Info = ItemData.getItemInfoByCode(code);
                        $('item_name', node).setString(Item_Info.Name);

                        downLoadImage(Item_Info.ImgBig, function (texture) {
                            $('item', node).removeAllChildren();
                            var sp = new cc.Sprite(texture);
                            $('item', node).addChild(sp);
                        });
                        // loadUrlImageToSprite(Item_Info.ImgBig, $('item', node));

                        $('item_num', node).setString('x' + num);
                        $('item_time', node).setString(seconds > 0 ? seconds + 's' : "");
                        var ava = Item_Info.AvailableOn; //0 数量 1 时间
                        $('item_num', node).setVisible(ava == 0);
                        $('item_time', node).setVisible(ava == 1);

                        TouchUtil.setOnclickListener($('touch_item', node), function (sender) {
                            if (!that.tableview.isTouchMoved()){
                                //如果是话费 就充值
                                if (Item_Info.TagType == that.TagType[1]) {
                                    that.showChargeIphoneLayer(Item_Info); //充值
                                    return;
                                }
                                if (that.showDesc) {
                                    $('tip_bg').setVisible(false);
                                    that.showDesc = false;
                                    return;
                                }
                                var Describe = Item_Info.Describe;
                                var width = node.getContentSize().width * 0.2;
                                var height = node.getContentSize().height * 0.7;
                                var pos = node.getNodeToWorldTransform();
                                $('tip_bg').setVisible(true);
                                $('tip_bg').setPosition(pos.tx + width, pos.ty + height);
                                $('tip_bg.lb_desc').setString(Describe);
                                that.showDesc = true;
                            }
                        }, {"swallowTouches": false});

                    }
                })(i);


            }
            return cell;
        },
        numberOfCellsInTableView: function (table) {
            return Math.ceil(this.CurBagData.length / 4);

        },

        showChargeIphoneLayer: function (Item_Info, value) {
            $('charge_call_node').setVisible(true);
            TouchUtil.setOnclickListener($('charge_call_node.btn_close'), function (node) {
                $('charge_call_node').setVisible(false);
            });

            $('charge_call_node.lb_charge_num').setString(Item_Info.FaceValue / 100 + "元");


            var v_input1 = $('charge_call_node.input_call1');
            v_input1.setTextVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM);
            // v_input1.setPlaceHolderColor(cc.color(255, 255, 255, 255));
            v_input1.addEventListener(function (sender, type) {
                switch (type) {
                    case ccui.TextField.EVENT_ATTACH_WITH_IME: //点开输入框
                        break;
                    case ccui.TextField.EVENT_DETACH_WITH_IME://输入完毕
                        $('charge_call_node').setPositionY(0);
                        break;
                    case ccui.TextField.EVENT_INSERT_TEXT://插入字符
                        break;
                    case ccui.TextField.EVENT_DELETE_BACKWARD://点击enter
                        break;
                    default:
                        break;
                }
            });

            var v_input2 = $('charge_call_node.input_call2');
            v_input2.setTextVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM);
            // v_input2.setPlaceHolderColor(cc.color(255, 255, 255, 255));
            v_input2.addEventListener(function (sender, type) {
                switch (type) {
                    case ccui.TextField.EVENT_ATTACH_WITH_IME: //点开输入框
                        break;
                    case ccui.TextField.EVENT_DETACH_WITH_IME://输入完毕
                        $('charge_call_node').setPositionY(0);
                        break;
                    case ccui.TextField.EVENT_INSERT_TEXT://插入字符
                        break;
                    case ccui.TextField.EVENT_DELETE_BACKWARD://点击enter
                        break;
                    default:
                        break;
                }
            });
            TouchUtil.setOnclickListener($('charge_call_node.btn_charge'), function (node) {
                var input1Str = v_input1.getString();
                var m_AllNum1 = /^[0-9]\d*$/.test(input1Str);
                if (!m_AllNum1 || input1Str.length != 11 || input1Str[0] == '0') {
                    showAlert("输入的手机号有误!");
                    return;
                }
                var input2Str = v_input2.getString();
                if (input2Str != input1Str) {
                    showAlert("两次输入的手机号不一致!");
                    return;
                }

                var data = {
                    UserID: gameData.uid + "",
                    GameID: app.area + "",
                    AppID:app.appId + "",
                    Code: Item_Info.Code + "",
                    Value: 1,
                    Mobile: input2Str + "",
                    IsSendNotice: 0  //是否发送道具变更通知（只是道具） 0:不发送，1:发送
                };
                network.sendProto(1067, data);

                $('charge_call_node').setVisible(false);
            });


            this.addListener(1068, function (data) {
                hideLoading();

                showAlert("充值成功，请耐心等待!")
                var GoodsInfo = data.GoodsInfo; //道具变化基本信息{}
                // required string Code 			= 1;	//道具Code
                // required int64 ChangeQuantity   = 2;	//变化数量 数量或者有效时间秒
                // required int64 NowQuantity 	    = 3;	//现在道具数量
                // required int64 Seconds 	        = 4;	//时间类型道具剩余秒数
                // required int32 IsWare           = 5;    //是否装备中

                var data = {
                    UserID: gameData.uid + "",
                    GameID: app.area + "",
                    AppID:app.appId + "",
                    GoodsKeys: []  //获取所有道具
                }
                network.sendProto(1055, data);


            });


        },


    });
    exports.BagLayer = BagLayer;

})(window);